(function(){
	var elCurrent, elHolder, idProduct, idProperty = -1;
		classIconPlus = "icon-plus",
		classIconMinus = "icon-minus",
		classIconBack = "btn-back",
		classIconSave = "btn-save",
		classDisplay = "dd-display",
		classProductPic = "imageProduct",
		idTableDetail = "product_detail",
		idTableProperty = "product_property",
		jsonProperty = new Array(), //collect all the changed property info
		jsonDelete = new Array();
				
	var oTable = $('#' + idTableProperty).dataTable({
		// set the initial value
		"sDom": "<'row-fluid'><'row-fluid'>",
		"sPaginationType": "bootstrap",
		"sInitialType": "product_detail",
		"bSort": false,
		"oLanguage": {
			"sEmptyTable": "没有产品，请添加"
		},
	});
	

	idProduct = $('#' + idTableDetail).data("id");
	oTable.fnReloadAjax( 'file:///E:/MobSol/PupilBeast-Web/Admin%20Web/data/pd.txt',jsonProperty );
		idProduct=$("#product_detail").data("id");
	// var new_url="/app_admin/data/product_attr-data.json/"+idProduct+"/";
	// oTable.fnReloadAjax( new_url,jsonProperty );
    
	jQuery('#' + idTableProperty + '.group-checkable').change(function () {
		var set = jQuery(this).attr("data-set");
		var checked = jQuery(this).is(":checked");
		jQuery(set).each(function () {
			 if (checked) {
				  $(this).attr("checked", true);
			 } else {
				  $(this).attr("checked", false);
			 }
		});
		jQuery.uniform.update(set);
	});
	
	// jQuery('#editable-sample_wrapper .dataTables_filter input').addClass(" medium"); // modify table search input
	// jQuery('#editable-sample_wrapper .dataTables_length select').addClass(" xsmall"); // modify table per page dropdown

	$(document).on("click", "." + classIconPlus, function(e){
		//icon plus click function when in first tab
		if ($("#tab_1_1").hasClass("active") == true){
			if ($("#tab_1_1").find("td").length <= 4){
				var elTd = '<td style="float:left; vertical-align:middle"><input type="checkbox" class="checkboxes" value="1"/></td>'+
							'<td style="float:left">'+
								'<image class="imageProduct" id="image' + idProperty + '" src="img/NewProduct.png">'+
								'<input class="dd-file" id="imgPic' + idProperty + '" type="file" name="uploadImg">'+
							'</td>';
				idProperty += -1;
				$("#tab_1_1").find("tr").append(elTd);
			}else{
				swal("图片数量限制", "最多只能添加三个产品图片！", "warning");
			}
		}
		//icon plus click function when in second tab				
		if ($("#tab_1_2").hasClass("active") == true){
			e.preventDefault();
			var nTr = $('<tr class="odd gradeX" data-id="' + idProperty + '">'+
							'<td><input type="checkbox" class="checkboxes" value="1" /></td>'+
							'<td><input class="dd-display  inputName" value="单击输入名字"/></td>'+
							'<td class="hidden-phone"><textarea class="small dd-display textareaValue">单击输入值</textarea></td>'+
							'<td class="hidden-phone">'+
								'<img class="dd-property" src="img/NewProduct.png">'+
								'<input class="dd-file" id="imgProp' + idProperty + '" type="file" name="uploadImg">'+
							'</td>'+
							'<td class="center hidden-phone"><textarea class="small dd-display textareaDesp">单击输入图片描述</textarea></td>'+
						'</tr>')[0];
			idProperty -= 1;
			oTable.fnAddTr(nTr);

			// edit property name
			$("." + classDisplay).watch(function(value, el){
				updateArrayChangedProperty("name", value, el, jsonProperty);
			});
		}
	});
	
	//delete picture or property item depending on the tab active
	$(document).on('click', "." + classIconMinus, function(){
		//icon plus click function when in first tab
		if ($("#tab_1_1").hasClass("active") == true){
			if ($("input[type='checkbox']:checkbox:checked").length > 0){
				//delete warning
				swal({
						title: "真的决定删除吗?",
						text: "将无法恢复要删除的图片！",
						type: "warning",
						showCancelButton: true,
						confirmButtonColor: "#DD6B55",
						confirmButtonText: "决定删除",
						cancelButtonText: "取消",
						closeOnConfirm: false
					}, 
					function(){
						$("input[type='checkbox']:checkbox:checked").each(function(e){
							// Immediately remove the picture
							var elHandler, idImage, 
								elCurrent = $($(this).parent());
							
							elHandler = elCurrent.next();
							idImage = parseInt(elHandler.find('img').attr('id').replace('image',''));
							elCurrent[0].remove();
							elHandler[0].remove();
							if (idImage > 0) {
								//if product image to be delete on server, push to array to send to server
								jsonDelete.push(idImage);
							}
						});
						if (jsonDelete.length > 0){
							//	swal("write ajax after deleting images", 'haha');
                            var jsonPropertyDelete = JSON.stringify(jsonDelete)
							alert(jsonPropertyDelete);
							
							function handleAjax(){
								$.ajax({ 
									async: false,
									type : "POST",
								//    dataType : 'Text', 
									contentType : 'application/json',
									url:"/app_admin/handle_product_pic_delete/",
									data : jsonPropertyDelete,
								
									error:function(result){
										//upload tree ajax failed
										//info user to continue editing or save again
										swal({
												title: "删除失败",
												text: "是否要重新删除呢？如果取消可以继续编辑。",
												type: "warning",
												showCancelButton: true,
												confirmButtonColor: "#DD6B55",
												confirmButtonText: "继续删除",
												cancelButtonText: "取消",
												closeOnConfirm: false 
											}, 
											function(){
												//swal("继续执行删除", "尝试上一次删除内容", "error"); 
												//deleted already, append ajax to server again
												handleAjax();
										});					
									},
									
									success:function(result){
										swal({   
											title: "删除成功",   
											text: "可以继续编辑了！",
											confirmButtonText: "知道了" 
										});
									}
								});	
							}
							
							handleAjax();
						}
						//放在成功里，注释以后删除
						swal({
							title: "删除成功",
							text: "可以继续编辑了！",
							confirmButtonText: "知道了"
						});
					});
			}else{
				swal("没有图片选中", "请选择要删除的图片", "warning"); 
			}
		}
		//icon plus click function when in second tab				
		if ($("#tab_1_2").hasClass("active") == true){
			if ($("input[type='checkbox']:checkbox:checked").length > 0){
				//delete warning
				swal({
						title: "真的决定删除吗?",
						text: "将无法恢复要删除的属性！",
						type: "warning",
						showCancelButton: true,
						confirmButtonColor: "#DD6B55",
						confirmButtonText: "决定删除",
						cancelButtonText: "取消",
						closeOnConfirm: false
					}, 
					function(){
						$("input[type='checkbox']:checkbox:checked").each(function(){
							// Immediately remove the first producted
							oTable.fnDeleteRow( oTable.fnGetPosition(this.closest("tr")));
							
							updateArrayChangedProperty("delete", "", this, jsonProperty);
							
							if (parseInt($(this.closest("tr")).data("id")) > 0) {
								//if products to be delete on server, push to array to send to server
								jsonDelete.push($(this.closest("tr")).data("id"));
							}
						});
						
						// if array is not zero length, push array to server to delete products
						if (jsonDelete.length > 0){
							var jsonPropertyDelete = JSON.stringify(jsonDelete)
							alert(jsonPropertyDelete);
							
							function handleAjax(){
								$.ajax({ 
									async: false,
									type : "POST",
								//    dataType : 'Text', 
									contentType : 'application/json',
									url:"/app_admin/handle_product_attr_delete/",
									data : jsonPropertyDelete,
								
									error:function(result){
										//upload tree ajax failed
										//info user to continue editing or save again
										swal({
												title: "删除失败",
												text: "是否要重新删除呢？如果取消可以继续编辑。",
												type: "warning",
												showCancelButton: true,
												confirmButtonColor: "#DD6B55",
												confirmButtonText: "继续删除",
												cancelButtonText: "取消",
												closeOnConfirm: false 
											}, 
											function(){
												//swal("继续执行删除", "尝试上一次删除内容", "error"); 
												//deleted already, append ajax to server again
												handleAjax();
										});					
									},
									
									success:function(result){
										swal({   
											title: "删除成功",   
											text: "可以继续编辑了！",
											confirmButtonText: "知道了" 
										});
									}
								});	
							}
							
							handleAjax();
						}
				});	
			}else{
				swal("没有属性选中", "请选择要删除的属性", "warning"); 
			}
		}
		
		// after deleting, clean the jason
		jsonDelete =  Array();
	});

	//when click back button, return to product list
	$(document).on("click", "." + classIconBack, function handle(){
		self.location="/app_admin/product_list/";
	});
	
	//when click save button, send JSON and images to server
	$(document).on("click", "." + classIconSave,function handle(){

		//icon save click function when in first tab
		if ($("#tab_1_1").hasClass("active") == true){
			var data, elInput, idImage;
			
			$("#product_picture").find("img").each(function(){
				idImage = parseInt($(this).attr("id").replace('image',''));
				elInput = $(this).next();	
				if (elInput.val()){
					var data={'id': idImage};
					data['table_class']='ProductPicture';
                    data['product_id']= idProduct;
					ajaxFileUpload(elInput.attr("id"),data);
				}
			});
            
            //ajax to upload image
            function ajaxFileUpload(fileElementId,data) {
                 var url="/upload_image";
                 $.ajaxFileUpload
                 (
                      {
                            url: url, //用于文件上传的服务器端请求地址
                            type: 'post',
                            data: data, //此参数非常严谨，写错一个引号都不行
                            secureuri: false, //一般设置为false
                            fileElementId: fileElementId, //文件上传空间的id属性  <input type="file" id="file" name="file" />
                            dataType: 'json', //返回值类型 一般设置为json
                            success: function (data, status)  //服务器成功响应处理函数
                            {
								if (typeof (data.new_id) != 'undefined'){
									$(this).attr('id', 'image' + data.new_id);
								}
							},
                            error: function (data, status, e)//服务器响应失败处理函数
                            {
								swal('保存失败', '请重新保存！ 错误信息：' + e);
                            }
                      }
                 ) 
                 return false;
            } 
			
		}
		//icon save click function when in second tab				
		if ($('#tab_1_2').hasClass('active') == true){
			if (jsonProperty.length == 0){
				swal("没有任何改动需要保存","继续修改产品属性吧！");
			}else{
				var stringJsonProperty,
					keyIdProduct = 'idProduct',
					keyChildren = 'children';

				stringJsonProperty = '{"idProduct":' + idProduct + ', ' + '"children":' + JSON.stringify(jsonProperty) + '}';
				alert(stringJsonProperty);
				
				//send property chanded info (except image) ajax to server
				$.ajax({ 
				//    async: false,
					type : "POST",
				//    dataType : 'Text', 
					contentType : 'application/json',
					url:"/app_admin/handle_product_attr_update/",
					data : stringJsonProperty,
					
					error:function(result){
						swal({
								title: "保存失败",
								text: "网络问题导致更新失败 :-(",
								type: "warning",
								showCancelButton: true,
								confirmButtonColor: "#DD6B55",
								confirmButtonText: "继续上传",
								cancelButtonText: "取消",
								closeOnConfirm: false
							},
							function(){
								//swal("继续执行删除", "尝试上一次删除内容", "success");
								//deleted already, append ajax to server again
								handle();
						});
					},
					
					success:function(result){
						//update property id
						var strJson =result,
							elsProperty,
							keyOldId = "old_id",
							keyNewId = "new_id",
							str4UploadId = "imgProp",
							classFile = "dd-file",
							listJson = eval("("+strJson+")");

						elsProperty = $('#' + idTableProperty + ' tr');
						elsProperty.each(function(){
							var elProperty = $(this),
								idHandle = elProperty.data("id");
							
							//update category ID from server before upload images
							for (var i=0; i< listJson.length; i++){
								if (idHandle == listJson[i].keyOldId){
									//update data-id for new property
									elProperty.data("id", listJson[i].keyNewId);
									//update id in input of class="dd-file"
									elProperty.children("." + classFile).attr("id", str4UploadId + listJson[i].keyNewId);
								}
							}
						});
						
						//upload image
						var elImageInput,
							elsImageInput = $('#' + idTableProperty + ' .' + classFile);
						
						elsImageInput.each(function(){
							elImageInput = $(this);
							if (elImageInput.val()){
								var data={'id':elImageInput.closest("tr").data("id")};
								data['table_class']='ProductAttr';
								alert('1111')
								alert(elImageInput.attr("id"))
								alert(JSON.stringify(data))
								ajaxFileUpload(elImageInput.attr("id"),data); 
							}
						});
						
						
						//ajax to upload image
						function ajaxFileUpload(fileElementId,data){
							 // 开始上传文件时显示一个图片
							 /*    $("#lodingId"+item['id']).ajaxStart(function() {
								  $(this).show();
							 // 文件上传完成将图片隐藏起来
							 }).ajaxComplete(function() {
								  $(this).hide();
							 });
							 */ 
							var url="/upload_image";
							$.ajaxFileUpload
							(
								{
									url: url, //用于文件上传的服务器端请求地址
									type: 'post',
									data: data, //此参数非常严谨，写错一个引号都不行
									secureuri: false, //一般设置为false
									fileElementId: fileElementId, //文件上传空间的id属性  <input type="file" id="file" name="file" />
									dataType: 'json', //返回值类型 一般设置为json
									success: function (data, status)  //服务器成功响应处理函数
									{
									//    console.log("data.url = "+data.url) ;
									//    $("#img1").attr("src", data.url);
									//    alert("你请求的Id是" + data.Id + "     " + "你请求的名字是:" + data.name);
										 if (typeof (data.error) != 'undefined') {
											  if (data.error != '') {
													alert(data.error);
											  } else {
													alert(data.msg);
											  }
										 }
									},
									error: function (data, status, e)//服务器响应失败处理函数
									{
										 alert(e);
										 console.log("e = "+e) ;
									}
								}
							)
							return false;
						}
						jsonProperty = Array();
						//此函数放在成功返回函数里
						swal({
							title: "上传成功",
							text: "可以继续编辑了！",
							confirmButtonText: "知道了"
						});
					}
				});
			}
		}
	});
        
})();